package com.example.sentrytester;

import io.sentry.Sentry;
import io.sentry.SentryClient;
import io.sentry.connection.EventSendCallback;
import io.sentry.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

@Configuration
public class ApplicationConfig {
    private static Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

    @Bean
    public SentryClient sentryClient() {
        // use the SENTRY_DSN environment or the JVM property -Dsentry.dsn=http(s)://<key>@host/project
        SentryClient sentryClient = Sentry.init();
        sentryClient.setEnvironment("sentry-tester");
        sentryClient.setRelease("release 3.15");
        sentryClient.addTag("service", "sentry-dsn-tester");

        sentryClient.addShouldSendEventCallback(event -> {
            logger.info("Event {} to be sent.", event);
            return true;
        });

        sentryClient.addEventSendCallback(new EventSendCallback() {
            @Override
            public void onFailure(Event event, Exception exception) {
                logger.info("Event {} was failed with exception {}", event, exception);
            }

            @Override
            public void onSuccess(Event event) {
                logger.info("Event {} was sent to Sentry server.", event);
            }
        });

        return sentryClient;
    }

    @PreDestroy
    public void destroy() {
        logger.info("Closing the sentry connection.");
        sentryClient().closeConnection();
    }
}
